<template>
  <div class="problem-container">
    <!-- 顶部标题 -->
    <a-typography-title class="page-title" :heading="5">
      <icon-code /> 题库
    </a-typography-title>
    <a-button
      type="text"
      size="small"
      @click="handleRefresh"
      class="refresh-btn"
    >
      <template #icon>
        <icon-refresh :class="{ 'icon-spin': isLoading }" />
      </template>
      刷新
    </a-button>

    <!-- 题目列表 -->
    <a-list
      class="problem-list"
      :bordered="false"
      :split="false"
      :data="problemList"
    >
      <template #item="{ item, index }">
        <a-list-item class="problem-item">
          <div
            class="problem-card"
            @click="goToProblem(item.id, item.judgeInfo)"
          >
            <div class="problem-content">
              <!-- 题目序号 -->
              <div class="problem-number">
                {{ index + 1 }}
              </div>

              <!-- 题目信息 -->
              <div class="problem-info">
                <div class="problem-header">
                  <a-typography-title class="problem-title" :heading="6">
                    {{ item.title }}
                  </a-typography-title>
                </div>

                <a-typography-text class="problem-description">
                  {{ item.description }}
                </a-typography-text>

                <!-- 判题信息 -->
                <div v-if="item.judgeInfo" class="judge-info">
                  <a-tag :color="getJudgeInfoColor(item.judgeInfo)">
                    {{ item.judgeInfo }}
                  </a-tag>
                </div>

                <div class="problem-footer">
                  <div class="problem-meta">
                    <span class="meta-item">
                      <icon-clock-circle />
                      {{ item.timeLimit }}ms
                    </span>
                    <span class="meta-item">
                      <icon-storage />
                      {{ item.memoryLimit }}B
                    </span>
                    <span class="meta-item">
                      <icon-storage />
                      {{ item.stackLimit }}B
                    </span>
                  </div>
                  <a-button
                    type="primary"
                    class="solve-btn"
                    :disabled="item.judgeInfo === 'Accepted'"
                    @click.stop="goToProblem(item.id, item.judgeInfo)"
                  >
                    <icon-play-arrow /> 去做题
                  </a-button>
                </div>
              </div>
            </div>
          </div>
        </a-list-item>
        <a-divider :size="0" />
      </template>
    </a-list>
    <div class="countdown" :class="{ warning: timeLeft <= 60 }">
      {{ formattedTime }}
    </div>
    <a-button
      type="primary"
      style="min-width: 200px; margin-left: 50px"
      @click="handleSubmitClick"
    >
      提交结果
    </a-button>
  </div>
  <!-- 提交确认弹窗 -->
  <a-modal
    v-model:visible="showSubmitDialog"
    :simple="false"
    title="确认提交"
    @ok="handleConfirmSubmit"
    @cancel="showSubmitDialog = false"
    :hide-cancel="false"
    class="submit-dialog"
  >
    <template #title>
      <div class="dialog-title">
        <icon-exclamation-circle class="title-icon" />
        确认提交所有题目？
      </div>
    </template>

    <div class="dialog-content">
      <p class="tip-text">提交后你将无法继续修改答案</p>
      <p class="detail-text">
        <icon-exclamation /> 请确认你已经完成所有题目的作答<br />
        <icon-exclamation /> 未完成的题目将被视为未通过
      </p>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <a-button
          type="secondary"
          @click="showSubmitDialog = false"
          class="cancel-btn"
        >
          再检查一下
        </a-button>
        <a-button
          type="primary"
          status="danger"
          @click="handleConfirmSubmit"
          class="confirm-btn"
        >
          确认提交
        </a-button>
      </div>
    </template>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, watch, onUnmounted } from "vue";
import { useRouter } from "vue-router";
import {
  IconCode,
  IconClockCircle,
  IconStorage,
  IconPlayArrow,
} from "@arco-design/web-vue/es/icon";
import { CompetitionControllerService } from "../../../generatedCom/services/CompetitionControllerService";
import { Message } from "@arco-design/web-vue";
const router = useRouter();

// 模拟题目数据
// [
//   {
//     id: 1,
//     title: "两数之和",
//     description:
//       "给定一个整数数组 nums 和一个目标值 target，请你在该数组中找出和为目标值的两个整数。",
//     timeLimit: 1000,
//     memoryLimit: 256,
//     stackLimit: 1024,
//     judgeInfo: "Accept", // 示例数据
//   },
//   {
//     id: 2,
//     title: "反转链表",
//     description: "反转一个单链表，要求使用迭代或递归两种方式实现。",
//     timeLimit: 1500,
//     memoryLimit: 256,
//     stackLimit: 1024,
//     judgeInfo: "Pending", // 示例数据
//   },
//   // 更多题目...
// ]
const problemList = ref();
const formData = ref();
onMounted(async () => {
  // 根据比赛id获取题目列表
  // 从路由中获取比赛id
  // const id = router.currentRoute.value.params.id;
  const idParam = router.currentRoute.value.params.id ?? "";
  const id = Array.isArray(idParam)
    ? parseInt(idParam[0], 10)
    : parseInt(idParam, 10);

  const res =
    await CompetitionControllerService.getCompetitionQuestionUsingPost({
      id: id,
    });
  console.log(res);
  problemList.value = res.data.competitionQuestions;
  formData.value = res.data.timeLimit;
});

// 跳转到题目详情
const goToProblem = (id: number, judgeInfo: string) => {
  if (judgeInfo !== "Accepted") {
    router.push(`/problem/${id}`);
  }
};
// 新增加载状态
const isLoading = ref(false);

// 刷新处理函数
const handleRefresh = async () => {
  isLoading.value = true;
  try {
    const idParam = router.currentRoute.value.params.id ?? "";
    const id = Array.isArray(idParam)
      ? parseInt(idParam[0], 10)
      : parseInt(idParam, 10);
    const res =
      await CompetitionControllerService.getCompetitionQuestionUsingPost({
        id,
      });
    problemList.value = res.data.competitionQuestions;
    formData.value = res.data.timeLimit;
  } finally {
    isLoading.value = false;
    Message.success("刷新成功");
  }
};
// 根据判题信息获取标签颜色
const getJudgeInfoColor = (judgeInfo: string) => {
  switch (judgeInfo) {
    case "Accepted":
      return "green";
    case "Pending":
      return "orange";
    case "Wrong Answer":
      return "red";
    default:
      return "blue";
  }
};
// 修改倒计时逻辑
const startTimer = () => {
  if (timer) clearInterval(timer);
  timer = setInterval(() => {
    if (timeLeft.value > 0) {
      timeLeft.value--;
    } else {
      clearInterval(timer!);
      handleConfirmSubmit();
      showTimeoutDialog.value = true; // 显示弹窗
      setTimeout(() => {
        router.push("/my/complete"); // 3秒后跳转
      }, 3000);
    }
  }, 1000);
};

// 格式化时间显示
const formattedTime = computed(() => {
  const minutes = Math.floor(timeLeft.value / 60);
  const seconds = timeLeft.value % 60;
  return `${minutes.toString().padStart(2, "0")}:${seconds
    .toString()
    .padStart(2, "0")}`;
});

const timeLeft = ref(0);
// 修改后
let timer: ReturnType<typeof setInterval> | null = null;
// 新增响应式变量
const showTimeoutDialog = ref(false);
// 监听formData变化初始化倒计时
watch(
  () => formData.value,
  (newVal) => {
    if (newVal) {
      timeLeft.value = newVal;
      startTimer();
    }
  }
);
// 组件卸载时清除定时器
onUnmounted(() => {
  if (timer) clearInterval(timer);
});
// 新增响应式变量
const showSubmitDialog = ref(false);

const handleSubmitClick = () => {
  console.log("提交代码");
  showSubmitDialog.value = true;
};
const handleConfirmSubmit = async () => {
  const idParam = router.currentRoute.value.params.id ?? "";
  const id = Array.isArray(idParam)
    ? parseInt(idParam[0], 10)
    : parseInt(idParam, 10);
  const res =
    await CompetitionControllerService.publishCompetitionQuestionUsingPost({
      id,
    });
  console.log(res);
  Message.success("提交成功");
  showSubmitDialog.value = false;
  router.push("/my/complete");
};
</script>

<style scoped>
/* 页面容器 */
.problem-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem 1.5rem;
}

/* 页面标题 */
.page-title {
  color: var(--color-text-1);
  margin-bottom: 2rem;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

/* 题目列表 */
.problem-list {
  background: transparent;
}

/* 题目卡片 */
.problem-card {
  background: var(--color-bg-2);
  border-radius: 12px;
  padding: 1.5rem;
  transition: all 0.3s ease;
  cursor: pointer;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    background: var(--color-bg-3);
  }
}
/* 倒计时样式 */
.countdown {
  font-size: 24px;
  font-weight: bold;
  text-align: center;
  margin: 20px 0;
  padding: 12px 24px;
  background: #f5f5f5;
  border-radius: 8px;
  display: inline-block;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.countdown.warning {
  color: #ff4d4f;
  background: #fff2f0;
  animation: pulse 1s infinite;
}

.problem-content {
  display: flex;
  gap: 1.5rem;
  align-items: flex-start;
}

/* 题目编号 */
.problem-number {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  background: var(--color-primary-light-1);
  color: var(--color-primary);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.5rem;
  font-weight: 600;
  flex-shrink: 0;
}

/* 题目信息 */
.problem-info {
  flex: 1;
}

.problem-header {
  display: flex;
  align-items: center;
  gap: 1rem;
  margin-bottom: 0.8rem;
}

.problem-title {
  margin: 0 !important;
}

.problem-description {
  color: var(--color-text-2);
  line-height: 1.6;
  margin-bottom: 1.2rem;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

/* 判题信息 */
.judge-info {
  margin-bottom: 1rem;
}

/* 题目底部 */
.problem-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.problem-meta {
  display: flex;
  gap: 1.5rem;
  color: var(--color-text-3);
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 0.3rem;
}

/* 按钮样式 */
.solve-btn {
  border-radius: 6px;
  padding: 0.5rem 1.2rem;
  transition: all 0.2s ease;

  &:hover {
    transform: scale(1.05);
  }
}

/* 难度标签 */
.problem-difficulty {
  border-radius: 4px;
  font-weight: 500;
}
/* 提交弹窗样式 */
:deep(.submit-dialog .arco-modal-header) {
  border-bottom: none;
  padding-bottom: 0;
}

.dialog-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 20px;
  color: var(--color-text-1);

  .title-icon {
    color: rgb(var(--primary-6));
    font-size: 24px;
  }
}

.dialog-content {
  padding: 16px 0;
  text-align: center;

  .tip-text {
    font-size: 16px;
    color: var(--color-text-2);
    margin-bottom: 12px;
  }

  .detail-text {
    font-size: 14px;
    color: var(--color-text-3);
    line-height: 1.8;
    text-align: left;
    background: var(--color-fill-2);
    padding: 12px;
    border-radius: 4px;

    .arco-icon {
      color: var(--color-text-3);
      margin-right: 4px;
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 16px;
  margin-top: 24px;

  .cancel-btn {
    min-width: 100px;
  }

  .confirm-btn {
    min-width: 100px;
    background-color: rgb(var(--primary-6));
    transition: all 0.2s;

    &:hover {
      opacity: 0.9;
      transform: translateY(-1px);
    }
  }
}
.refresh-btn {
  background-color: #f0f8ff; /* 淡蓝背景 */
  color: #007acc; /* 字体颜色 */
  border: 1px solid #d1e7fd; /* 边框颜色 */
  border-radius: 6px; /* 圆角 */
  padding: 8px 16px; /* 内间距调整 */
  transition: all 0.3s ease; /* 平滑过渡效果 */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); /* 添加阴影 */
}

.refresh-btn:hover {
  background-color: #e6f4ff; /* 鼠标悬浮时更亮的背景 */
  color: #005bb5; /* 鼠标悬浮时字体变深 */
  border-color: #b3d4fc; /* 鼠标悬浮时边框颜色 */
  transform: translateY(-2px); /* 鼠标悬浮时轻微向上 */
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15); /* 鼠标悬浮时加深阴影 */
}

.refresh-btn:active {
  background-color: #d9edf9; /* 鼠标按下的背景 */
  color: #003973; /* 鼠标按下字体颜色 */
  transform: translateY(1px); /* 鼠标按下微微下沉 */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); /* 阴影恢复 */
}
</style>
